package com.future.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * <P>
 *
 * </p>
 *
 * @author yinhao
 * @version 1.0
 * @since 2024/9/9 13:57
 */
public class MyBatisUtils {

    private static final SqlSessionFactory sqlSessionFactory;

    // 静态代码块,初始化sqlSessionFactory
    static {
        // 指定配置文件
        String resource = "mybatis-config.xml";
        // 获取配置文件对应的流
        try {
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 获取SqlSession对象
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}
